var core = require('core');
var util = core.util;
var wechat = core.wechat;
var qr = util.qrcode;
var sign = require('../sign')

var get = function(req, res, next){
    var query = req.query;
    var token = query.token;
    sign(token, function(doc){
        if(doc.code){
            doc.docs = {};
            req.error = doc;
            next();
        }else{
            var SEND = new core.send(0);
            SEND.docs = {
                token : token,
                jssdk : wechat.getJSSDK(req.originalUrl)
            };
            res.render("admin/merchant_add", SEND);
        }

    });
};

var post = function(req, res, next){
    var body = req.body;
    var token = body.token;
    sign(token, function(body){
        if(body.code){
            res.send(body);
        }else{
            core.api('open/setToken', {openid: body.docs.data.oid}, function(err, doc){
                if(!doc.code){
                    var url = wechat.config.URL + "open/merchant_create?token="+ doc.docs.token +"&ooid="+ body.docs.data.oid;
                    var options = {type: "png"};
                    var img = qr(url, options);
                    doc.docs = {
                        qrcode : img
                    };
                }
                res.send(doc);
            });
        }
    });
};

exports.GET = get;
exports.POST = post;
